from datetime import datetime, timezone
from django.core.management.base import BaseCommand
from announcements.models import Announcement, Notification, Image
import os
from django.conf import settings


class Command(BaseCommand):
    help = 'Deletes expired announcements and their related images and files'

    def handle(self, *args, **options):
        now = datetime.now(timezone.utc)
        announcements = Announcement.objects.all()

        for announcement in announcements:
            if announcement.date_of_expiring:
                if announcement.date_of_expiring <= now:

                    files = announcement.files.all()
                    images = Image.objects.filter(announcement_id=id)
                    notifications = Notification.objects.filter(announcement_id=announcement.id)

                    for file in files:
                        file.file.delete()
                        file.delete()

                    for image in images:
                        if settings.MEDIA_ROOT in image.image_url:
                            os.remove(settings.MEDIA_ROOT + image.image_url)
                            image.delete()

                    self.stdout.write(self.style.SUCCESS(f"Successfully deleted announcement with id {announcement.id} and it's related image and files."))
                    announcement.delete()
                    notifications.delete()
